# drf异常处理器
from rest_framework.views import exception_handler
# 响应结果
from rest_framework.response import Response
# 数据错误
from django.db import DataError
# 状态码
from rest_framework import status
import logging

logger = logging.getLogger('django')

def costom_exception_handler(exc,context):
    """
    自定义异常处理
    exc:exception 异常类
    context：上下文
    return : response 响应结果对象
    """
    # 调用drf框架原生的异常处理方法
    response = exception_handler(exc,context)

    if response is None:
        # 视图
        view = context['view']
        if isinstance(exc,DataError):
            # 数据库操作异常----日志记录报错信息
            logger.error("[%s] %s" % (view,exc))
            response = Response({"message":"服务器内部错误....."},status=status.HTTP_507_INSUFFICIENT_STORAGE)
        if isinstance(exc,ZeroDivisionError):
            logger.error("[%s] %s" % (view, exc))
            # 需要展示重定向页面，还是返回具体状态码，实际业务需求决定
            response = Response({"message": "服务器内部错误.....","code":"10005"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return response
